import { Component, Input, Output, HostListener, Renderer, ViewChild, ElementRef, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { SearchService, SearchType } from './search.service';

/**
 * Search main component
 *
 * Author: Sorin Spiru
 * Date: 13.01.2018
 */
@Component({
    moduleId: module.id,
    selector: 'search',
    templateUrl: 'search.component.html',
    styleUrls: ['search.component.scss'],
    providers: [SearchService]
})
export class SearchComponent {

    @ViewChild('searchElem') searchElem: ElementRef;

    @Input() searchType: SearchType;

    @Input() navigateTo: string;

    @Input() routeIdentifier: string;

    @Input() isDropDown: boolean = false;

    @Input() displayField: string;    

    @Input() allowNewEntry: boolean = false;

    private skip: number = 0;

    private take: number = 20;

    private returnCount: number = 0;

    public found: any[] = null;

    public term: string = '';

    public show: boolean = false;

    //used only if isDropDown
    public selected: any = null;

    constructor(
        private router: Router,
        private searchService: SearchService) {
    }

    @HostListener('document:click', ['$event'])
    onDocumentClick(e) {
        this.show = this.found != null && this.found.length > 0 && (this.searchElem.nativeElement as HTMLElement).contains(e.target);
    }

    public search() {
        this.returnCount = 0;
        this.skip = 0;
        if ((!this.isDropDown && this.term !== '') || this.isDropDown) {
            if(this.term == "") this.selected = null;
            this.searchService.search(this.searchType, this.term, this.skip, this.take).subscribe(data => {
                this.found = data;                          
                if(this.found.length == 0) this.selected = null;
                this.returnCount = data.length;
                this.show = true;
            });
        }
        else {
            this.found = [];
            this.show = false;
        }
    }

    public scroll(e) {
        //200 is the height of the result container
        if (this.returnCount == this.take && e.currentTarget.scrollTop + e.currentTarget.offsetHeight >= e.currentTarget.scrollHeight) {
            this.skip += this.take;
            this.searchService.search(this.searchType, this.term, this.skip, this.take).subscribe(data => {
                this.found = this.found.concat(data);
                this.returnCount = data.length;
            });
        }
    }

    public dropDownSelect(value: any) {
        this.selected = value;
        this.term = value[this.displayField];
        this.show = false;
    }
}